<template>
  <vue-office-docx
      :src="docx"
      style="height: 100vh;"
      @rendered="renderedHandler"
      @error="errorHandler"
  />
</template>

<script>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'

export default {
  components: {
    VueOfficeDocx
  },
  data() {
    return {
      docx: '',//设置文档网络地址，可以是相对地址
      startTime: '', // 开始阅读时间
      requiredTime: '', // 强制浏览时长（示例设为10秒）
      isCompleted: false,     // 是否完成阅读
      timer: null,            // 定时器
      baseUrl: `${encodeURIComponent('https://ycxueliang.cn/wages-admin/admin-api/infra/file')}`
    }
  },
  mounted() {
    const params = location.search.split('?')[1]
    const paramsArr = params.split('&')
    const relativeAddress = paramsArr[0].split('=')[1]
    this.requiredTime = paramsArr[1].split('=')[1]
    // const relativeAddress = location.search.split('=')[1]
    console.log(relativeAddress)

    // 记录进入时间并启动倒计时
    this.startTime = Date.now();
    this.timer = setTimeout(() => {
      this.isCompleted = true;
    }, this.requiredTime);

    // 监听页面关闭/刷新事件
    window.history.pushState(null,null,document.URL)
    window.addEventListener('beforeunload', this.handleBeforeUnload,false);
    this.docx = decodeURIComponent(this.baseUrl) + decodeURIComponent(relativeAddress)
  },
  beforeDestroy() {
    // 清除定时器和事件监听
    clearTimeout(this.timer);
    window.removeEventListener('beforeunload', this.handleBeforeUnload,false);
    // 离开时检测是否完成阅读
    if (!this.isCompleted) {
      this.showWarning();
    }
  },
  methods: {
    handleBeforeUnload(event) {
      window.history.pushState(null,null,document.URL)
      console.log(this.isCompleted)
      // 未完成时阻止关闭并提示
      if (!this.isCompleted) {
        event.preventDefault();
        event.returnValue = '您尚未阅读完毕，确定要离开吗？';
        this.showWarning();
      } else {
        localStorage.setItem('is_read_end','false')
      }
    },
    showWarning() {
      alert(`未达到最低阅读时间，请继续浏览 ${Math.ceil((this.requiredTime - (Date.now() - this.startTime))/1000)} 秒`);
    },
    renderedHandler(){
      console.log("渲染完成")
    },
    errorHandler() {
      console.log("渲染失败")
    }
  }
}
</script>